from lviewer.tools import latex, image
from lviewer.util.console import execute, ToolFailure
from lviewer.util import events
from lviewer.filechange import FileChangeMonitor
import tempfile
import os.path
import re
import shutil
import cgi

class LatexBuilder( object ):
    def __init__(self, filename):
        self.filename = filename
        self.temp_dir = tempfile.mkdtemp()
        self.changed  = events.Event()
        self.build()
        self.watcher = FileChangeMonitor( os.path.dirname(self.filename) )
        self.watcher.on_change.add_listener(self.build)
    
    def stop(self):
        self.watcher.stop()
        shutil.rmtree( self.temp_dir )

    def build(self):
        try:
            self.do_build()
        except ToolFailure:
            pass

        self.latex_output = cgi.escape(self.latex_output)
        self.latex_output = self.latex_output.replace("\n", "<br>")
        self.convert_output = cgi.escape(self.convert_output)
        self.convert_output = self.convert_output.replace("\n", "<br>")
        print self.latex_output
        print self.convert_output
        self.changed.fire()

    def reset(self):
        self.latex_output = ''
        self.convert_output = ''
        self.images = []
        self.good = False

    def do_build(self):
        self.reset()

        pdflatex = execute( [latex.pdflatex.path, 
            '--output-directory=%s' % self.temp_dir, 
            self.filename] )
        try:
            pdflatex.finish()
        finally:
            self.latex_output = pdflatex.stdout + "\n" + pdflatex.stderr

        pdf_name = os.path.basename( self.filename )
        pdf_name = os.path.splitext(pdf_name)[0] + '.pdf'
        
        self.images = self.build_images( pdf_name )
        self.good = True
    
    def build_images(self, pdf_name):
        convert = execute( [image.convert.path,
            os.path.join( self.temp_dir, pdf_name ),
            '-verbose',
            os.path.join( self.temp_dir, 'output.png' ) ] )
        try:
            convert.finish()
        finally:
            self.convert_output = convert.stdout + "\n" + convert.stderr

        images = []
        for line in convert.stdout.split('\n'):
            pos = line.find('=>')
            pos2 = line.find('PDF')
            pos3 = line.find('[')
            if pos3 != -1 and pos3 < pos2:
                pos2 = pos3

            if pos != -1 and pos2 != -1:
                filename = line[pos+2:pos2]
                images.append( filename.strip() )
        
        return images
        
